/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { BootloaderScanner } from './BootloaderScanner'
import hilog from '@ohos.hilog';
import { WorkerMsg } from '../../WorkMsg';
import { workScheduler } from '@kit.BackgroundTasksKit';

export class BootloaderScannerFactory {
  private static TAG = 'BootloaderScannerFactory';
  private static DOMAIN = 0x8632;

  /**
   * The bootloader may advertise with the same address or one with the last byte incremented
   * by this value. I.e. 00:11:22:33:44:55 -&gt; 00:11:22:33:44:56. FF changes to 00.
   */
  private static ADDRESS_DIFF: number = 1;

  private BootloaderScannerFactory() {}

  public static getIncrementedAddress(deviceAddress: string): string {
    let firstBytes: string = deviceAddress.substring(0, 15);
    let lastByte: string = deviceAddress.substring(15); // assuming that the device address is correct
    let lastNum: number = (parseInt(lastByte, 16) + this.ADDRESS_DIFF) & 0xFF;
    let lastByteIncremented: string = lastNum.toString(16).slice(-2);
    let res: string = firstBytes + lastByteIncremented;
    hilog.info(this.DOMAIN, this.TAG, `${deviceAddress} Incremented ${res}`)
    return res;
  }

  /**
   * Returns the scanner implementation.
   *
   * @return the bootloader scanner
   */
  public static getScanner(deviceAddress: string, serviceUuid: string, wmsg: WorkerMsg): BootloaderScanner {
    let deviceAddressIncremented: string = this.getIncrementedAddress(deviceAddress);

    return new BootloaderScanner(deviceAddress, deviceAddressIncremented, serviceUuid, wmsg);
    // return new BootloaderScannerJB(deviceAddress, deviceAddressIncremented);
  }
}